var config = require('../../config');
var accountService = require('../wechat/service/AccountService');
var commonService = require('../biz/common/service/CommonService');
var Promise = require('promise');
var wechatRest = require('./wechatRest');
var logger = require('log4js').getLogger('interceptor');

var interceptor = {};

//验证微信jsapi_ticket
interceptor.verifyJsTicket = function (req, res, next) {
    var account = req.session.account || null;
    Promise.resolve(account).then(function (_account) {
        if (!_account) {
            return accountService.getDefaultAccount().then(function (r) {
                account = r;
                req.session.account = r;
                return Promise.resolve(r);
            });
        } else {
            return Promise.resolve(_account);
        }
    }).then(function (_account) {
        return accountService.verifyAccessToken(req.session.account);
    }).then(function (_account) {
        return accountService.verifyJsTicket(req.session.account);
    }).done(function (_account) {
        next();
    }, function (err) {
        next(err);
    });
};


// 校验企业号的UserId信息
interceptor.verifyBaseAuth = function (req, res, next) {
    var fans = req.session.fans;
    if (!fans) {
        //没有授权
        //req.session.backUrl = req.originalUrl;
        var returnUrl = encodeURIComponent(req.originalUrl);
        res.redirect('/en_wechat/auth/base?state='+returnUrl);
    } else {
        next();
    }
};

// 校验微信用户的详细信息
interceptor.verifyUserAuth = function (req, res, next) {
    var fans = req.session.fans;
    if (!fans) {
        //没有授权
        var returnUrl = encodeURIComponent(req.originalUrl);
        logger.debug("---------------------------------------------------");
        logger.debug(req.originalUrl);
        res.redirect('/en_wechat/auth/user?state='+returnUrl);
    } else {
        next();
    }
};

//尝试获取用户信息(全平台)
interceptor.tryGetFans = function(req, res, next){
    var fans = req.session.fans;
    if (!fans) {
        // 跳过网页浏览
        if (req.get('user-agent').toLowerCase().indexOf('micromessenger') < 0) {
            var openId = "visitor" + new Date().getTime();
            req.session.fans = {
                openId : openId,
                nickname : '',
                authorize : 0
            };
            next();
            return;
        } else {
            var returnUrl = encodeURIComponent(req.originalUrl);
            res.redirect('/wechat/auth/base?state='+returnUrl);
        }
    } else {
        next();
        return;
    }
};

interceptor.verifySetting = function(req, res, next){
    var paths = req.baseUrl.split('/');
    if(paths[1]!="biz"){
        next();
    }else{
        var result = {};
        commonService.getSettingByKeyword(paths[2]).then(function(setting){
            result =  _checkSetting(setting);
            if(result.valid&&result.accountId){
                var account = req.session.account || {};
                if(result.accountId!=account.id){
                    return accountService.getById(result.accountId);
                }
            }
        }).done(function(_account){
            if(typeof _account ==='object'&&_account.id){
                req.session.account = _account;
            }
            if(result.auth){//需授权
                var fans = req.session.fans;
                if(!fans){
                    var returnUrl = encodeURIComponent(req.originalUrl);
                    res.redirect(result.authUrl+returnUrl);
                }else{
                    next();
                }
            }else if(result.valid){//活动有效
                next();
            }else{//过期
                res.render(result.expireUrl);
            }
        })
    }
};

function _checkSetting(setting){
    var result = {};
    var now = new Date();
    if(!setting){
        result.valid = true;
    }else if(setting.state==0||now<setting.startTime){//活动未开始
        result.valid = false;
    }else if(now>setting.endTime){//活动结束
        result.valid = false;
        result.expireUrl = setting.expireUrl||'system/views/404';
    }else{
        result.valid = true;
        result.accountId = setting.accountId;
        result.auth = false;
        switch(setting.authType){
            case 1 : {
                result.auth = true;
                result.authUrl = '/wechat/auth/base?state=';break;
            }
            case 2 : {
                result.auth = true;
                result.authUrl = '/wechat/auth/user?state=';break;
            }
        }
    }
    return result;
}

module.exports = interceptor;